import Qs from 'qs'

const formatJson  = function(json, options) {
	try {
		if (typeof json !== 'string') {
			json = JSON.stringify(json, null , 2);
		} else {
			json = JSON.parse(json);
			json = JSON.stringify(json, null, 2);
		}
		return json;
	}catch (e) {
		return json;
	}
}

/**
 * url转map
 * @param url
 */
const urlToMapArr = function (url) {
	if(!url){
		return {};
	}
	if(url.startsWith("http") && url.indexOf("?") === -1){
		return {};
	}
	if(url && url.indexOf('?') > -1){
		url = url.substring(url.indexOf('?'));
	}
	return Qs.parse(url, {arrayFormat: 'indices', allowDots: true});
}

/**
 * map转Url
 * @param params
 */
const mapToUrl = function(params){
	params = params || {};
	return Qs.stringify(params, { indices: false });
}

/**
 * 简单获取uuid
 */
const guid = function() {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
		.replace(/[xy]/g, function (c) {
			let r = Math.random() * 16 | 0,
				v = c === 'x' ? r : (r & 0x3 | 0x8);
			return v.toString(16);
		});
}

const base64toFile = function(dataUrl, filename = 'file') {
	let arr = dataUrl.split(',')
	let mime = arr[0].match(/:(.*?);/)[1]
	let suffix = mime.split('/')[1]
	let bstr = atob(arr[1])
	let n = bstr.length
	let u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], `${filename}.${suffix}`, {
		type: mime
	})
}

export {formatJson, urlToMapArr, mapToUrl, guid, base64toFile}
